<?php

/**
 * Must be implemented by all filters
 */
interface iFilter
{
	public function applyFilter($echo);	
}

/**
 * A class to manage application of filters to echos
 */
class FilterManager
{
	private $filters;
	
	/**
	 * So what happens is that we get the list of enabled filters from the config, then check to see if they
	 * exist.   If not, nothing happens, they get returned as failed filter imports to the caller
	 * 
	 * @return array The list of filters that failed to import
	 */
	public function __construct()
	{
		global $enabled_filters;
		$this->filters = array();
		$failedFilters = array();
		
		foreach($enabled_filters as $filter)
		{	
			if(file_exists(dirname(__FILE__) . "/{$filter}.php"))
			{
				require_once(dirname(__FILE__) . "/{$filter}.php");
				$this->filters[] = $filter;
			}
			else
			{
				$failed_filters[] = $filter;
			}
		}
		
		return $failed_filters;
	}
	
	/**
	 * Function to apply all of our filters to the echo
	 * 
	 * @param $echo array - The echo in the form of:<br/>
 	 * nickname => nickname of the user making the comment<br/>
 	 * replyto => (optional) who the comment is directed to<br/>
 	 * posted => What time (Japan) the comment was posted<br/>
 	 * comment => the comment made<br/>
 	 * selfnick => Your own nickname
	 */
	public function applyFilters($echo)
	{
		foreach($this->filters as $filter)
		{
			// the magic of variable variables
			// http://www.php.net/language.variables.variable
			$current_filter = new $filter();
			$result = $current_filter->applyFilter($echo);
			
			// In this case, a filter indicates the echo needs to be removed
			// return false to let the caller know to keep it out of the echo return
			if(!$result)
			{
				return false;
			}
			
			// We need the filtered version to come back
			$echo = $result;
			// This is in case other filters want to react based
			// on the existing application of another filter
			$echo['applied_filters'][] = $filter;
		}
		
		return $echo;
	}
}
?>
